﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Input;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml;
using System.ServiceModel.Syndication;
using QuickWeb.Resources;

namespace QuickWeb
{

    public partial class AddRSSFeedPage : PhoneApplicationPage, INotifyPropertyChanged 
    {

        private ProgressIndicator progressBar;
        private string readingURL;

        private FeedsStoredContext storedFeedsDB;
        private ObservableCollection<FeedStored> _FeedStoredItems;
        public ObservableCollection<FeedStored> FeedStoredItems
        {
            get
            {
                return _FeedStoredItems;
            }
            set
            {
                if (_FeedStoredItems != value)
                {
                    _FeedStoredItems = value;
                    NotifyPropertyChanged("FeedStoredItems");
                }
            }
        }


        public AddRSSFeedPage()
        {
            InitializeComponent();
            storedFeedsDB = new FeedsStoredContext(FeedsStoredContext.DBConnectionString);
            this.DataContext = this;
            progressBar = new ProgressIndicator();
            progressBar.IsVisible = true;
            SystemTray.SetProgressIndicator(this, progressBar);
            
        }





        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            var itemsInDB = from FeedStored item in storedFeedsDB.items
                            select item;
            FeedStoredItems = new ObservableCollection<FeedStored>(itemsInDB);
            base.OnNavigatedTo(e);
            


        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //Guardar los resultados e la abse de datos
            storedFeedsDB.SubmitChanges();
        }

        private void urlInput_GotFocus(object sender, RoutedEventArgs e)
        {
            urlInput.SelectAll();
        }





        private void urlInput_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (urlInput.Text.Length > 0)
                {
                    addFeed(urlInput.Text);
                    Focus();
                }
            }
        }

        public void addFeed(string feedUrl){
            urlInputPanel.Visibility = Visibility.Collapsed;
            progressBar.IsIndeterminate = true;//Indicador de que se esta cargando contenido            
            //FeedStored newfeed = new FeedStored();
            //newfeed.Source = urlInput.Text;
            //newfeed.Title = urlInput.Text;
            //newfeed.Description = urlInput.Text + " desc";
            //FeedStoredItems.Add(newfeed);
            //storedFeedsDB.items.InsertOnSubmit(newfeed);
            WebClient downloader = new WebClient();
            downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(feedDownloadStringCompleted);
            bool error = false;
            Uri feedUri = null;
            readingURL = urlInput.Text;
            try
            {
                feedUri = new Uri(urlInput.Text);
            }catch (Exception e)
            {
                error= true;
            }
            if (error || (feedUri==null))
            {
                showErrorMessage(AppResources.InvalidAddress);
                urlInputPanel.Visibility = Visibility.Visible;
                progressBar.IsIndeterminate = false;
                return;
            }
            downloader.DownloadStringAsync(feedUri);

        }

        ///Cuando la descarga de la informacion del feed esta completa(o ha fallado)
        private void feedDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
            if (e.Error != null)
            {
                showErrorMessage(e.Error.Message);
                urlInputPanel.Visibility = Visibility.Visible;
                progressBar.IsIndeterminate = false;//Indicador de que se esta cargando contenido                   
            }
            else
            {
                // Save the feed into the State property in case the application is tombstoned. 
                analizeReceivedSourceInfo(e);      

            }

        }

        private void analizeReceivedSourceInfo(DownloadStringCompletedEventArgs e)
        {
            StringReader stringReader = new StringReader(e.Result);
            //if(!e.Result.Contains("<rss")){
            //    showErrorMessage("Por el momento solo se aceptan feeds rss");
            //    urlInputPanel.Visibility = Visibility.Visible;
            //    progressBar.IsIndeterminate = false;//Indicador de que se esta cargando contenido   
            //    return;
            //}
            XmlReader xmlReader = XmlReader.Create(stringReader);
            SyndicationFeed feedReaded = SyndicationFeed.Load(xmlReader);
            if (feedReaded.Links.Count<=0) {
                showErrorMessage(AppResources.linkInfoRetrieveError);
                urlInputPanel.Visibility = Visibility.Visible;
                progressBar.IsIndeterminate = false;//Indicador de que se esta cargando contenido   
                return;
            }            
            FeedStored newfeed = new FeedStored();
            newfeed.Source = readingURL;
            if (feedNameInput.Text.Length == 0)
            {
                newfeed.Title = feedReaded.Title.Text;
            }
            else {
                newfeed.Title = feedNameInput.Text;
            }
            
            newfeed.Description = feedReaded.Description.Text;
            Uri link = feedReaded.Links.FirstOrDefault().Uri;
            newfeed.Link = link.OriginalString;            
            FeedStoredItems.Add(newfeed);
            storedFeedsDB.items.InsertOnSubmit(newfeed);    
        
            urlInputPanel.Visibility = Visibility.Visible;
            progressBar.IsIndeterminate = false;
            urlInput.Text = "";
            feedNameInput.Text = "";
            showMessage(AppResources.feedAddedCorrectly);
        }

        private void showErrorMessage(string msg)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Showing the exact error message is useful for debugging. In a finalized application, 
                // output a friendly and applicable string to the user instead. 
                MessageBox.Show(msg);                         
            });
        }

        private void showMessage(string msg)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Showing the exact error message is useful for debugging. In a finalized application, 
                // output a friendly and applicable string to the user instead. 
                MessageBox.Show(msg);                
            });
        }
        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }
}